package com.founder.android.util;

import android.os.Handler;
import android.util.Log;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.TaobaoRequest;
import com.taobao.api.TaobaoResponse;

public class AndroidTaobaoClient {
	
	private TaobaoClient client;
	
	public AndroidTaobaoClient(String serverUrl, String appKey, String appSecret) {
		client = new DefaultTaobaoClient(serverUrl, appKey, appSecret);
	}

	public <T extends TaobaoResponse> void execute(TaobaoRequest<T> request, TaobaoClientListener l)
			throws ApiException {
		execute(request, null, l);
	}

	public <T extends TaobaoResponse> void execute(TaobaoRequest<T> request,
			String session, TaobaoClientListener l) throws ApiException {
		Handler handler = new Handler();
		new RequestThread(request, session, l, handler).start();
	}

	class RequestThread<T extends TaobaoResponse> extends Thread {
		
		private TaobaoRequest<T> request;

		private String session;
		
		private Handler handler;
		
		private TaobaoClientListenerWrapper wrapper;
		
		RequestThread(TaobaoRequest<T> r, String s, 
				TaobaoClientListener l, Handler h) {
			request = r;
			session = s;
			handler = h;
			wrapper = new TaobaoClientListenerWrapper(l);
		}
		
		public void run() {
			try {
				TaobaoResponse response = client.execute(request, session);
				if (response == null) {
					throw new ApiException("Response is null");
				}
				Log.d("AndroidTaobaoClient", "body=" + response.getBody());
				if (response.isSuccess()) {
					wrapper.setSuccess(true);
					wrapper.setResponse(response);
				} else {
					throw new ApiException("Error_Response code:" + response.getErrorCode() + ", msg:" + response.getMsg());
				}
			} catch (ApiException e) {
				wrapper.setSuccess(false);
				wrapper.setException(e);
			}
			handler.post(wrapper);
		}
	}
	
	class TaobaoClientListenerWrapper implements Runnable {
		
		private TaobaoClientListener listener;
		
		private ApiException exception;
		
		private TaobaoResponse response;
		
		private boolean success;
		
		TaobaoClientListenerWrapper(TaobaoClientListener l) {
			listener = l;
		}
		
		@Override
		public void run() {
			if (success) {
				listener.onResponseSuccess(response);
			} else {
				listener.onResponseFailed(exception);
			}
		}

		public ApiException getException() {
			return exception;
		}

		public void setException(ApiException exception) {
			this.exception = exception;
		}

		public TaobaoResponse getResponse() {
			return response;
		}

		public void setResponse(TaobaoResponse response) {
			this.response = response;
		}

		public boolean isSuccess() {
			return success;
		}

		public void setSuccess(boolean success) {
			this.success = success;
		}
		
	}
}
